package com.miracle.yuanshen;

import android.Manifest;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.*;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import com.miracle.yuanshen.util.Constants;


public class MainActivity extends AppCompatActivity {

    private SmsObserver smsObserver;
    private final Handler smsHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            System.out.println("短信："+msg.toString());
        }
    };
    public int count=1;
    public int me = 30;



    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //申请权限
        permission_handle();

        // 测试按钮
        test_btn();

        // 短信监听
        sms_handle();


    }

    private void permission_handle(){
        if(Build.VERSION.SDK_INT>=23) {
            //判断是否拥有权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
                Log.i("MainActivity-> ", "READ_SMS 进行权限申请");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, 10000);
            } else {
                Log.i("MainActivity-> ", "READ_SMS 权限已授权");
            }

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
                Log.i("MainActivity-> ", "INTERNET 进行权限申请");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, 10000);
            } else {
                Log.i("MainActivity-> ", "INTERNET 权限已授权");
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void sms_handle(){
        this.findViewById(R.id.hello_btn);
        smsObserver = new SmsObserver(this, smsHandler);
        getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, smsObserver);
    }



    private void test_btn(){
        //*********点击按钮发送通知
        //得到按钮实例
        Button hellobtn = (Button)findViewById(R.id.hello_btn);
        //设置监听按钮点击事件
        hellobtn.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View v) {
                count++;
                //得到textview实例
                TextView hellotv = (TextView)findViewById(R.id.hello_txt);

                if (count%10==0){
                    me--;
                    if (me==0){
                        for (int i=5; i>0; i--){
                            Toast.makeText(MainActivity.this,i+"秒后自爆", Toast.LENGTH_SHORT).show();
                            send_notice("我真的死了", "我真的死了，启动自报程序\n"+i+"秒后自爆");
                            hellotv.setText("我真的死了，启动自报程序\n"+i+"秒后自爆");
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.exit(0);
                    }else {
                        //弹出Toast提示按钮被点击了
                        Toast.makeText(MainActivity.this,"我被点死了", Toast.LENGTH_SHORT).show();
                        send_notice("我被点死了", "上上下下左右左右BA\n我还有"+me+"条命呢");
                        hellotv.setText("上上下下左右左右BA，我还有"+me+"条命呢");
                    }
                }else {
                    //弹出Toast提示按钮被点击了
                    Toast.makeText(MainActivity.this,"我被点了一下", Toast.LENGTH_SHORT).show();
                    send_notice("我被点了一下", hellotv.getText().toString());

                    //读取strings.xml定义的hello_again信息并写到textview上
                    System.out.println("tv:"+hellotv.getText().toString() + " | btn:"+hellobtn.getText().toString());
                    if (hellobtn.getText().toString().equals("say hello")){
                        hellotv.setText(R.string.say_again);
                        hellobtn.setText(R.string.btn_again);
                    }else {
                        hellotv.setText(R.string.say_hello);
                        hellobtn.setText(R.string.btn_say);
                    }
                }

            }
        });
    }

    /**
     * 发送通知
     * @param title
     * @param content
     */
    private void send_notice(String title, String content){
        String CHANNEL_ID = "chat";
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //适配8.0
        if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "聊天信息",NotificationManager.IMPORTANCE_DEFAULT);
            mNotificationManager.createNotificationChannel(channel);
        }
        /**
         * 注意写上 channel_id，适配8.0，不用担心8.0以下的，找不到 channel_id 不影响程序
         */
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this,CHANNEL_ID)
                .setContentTitle(title)
                .setContentText(content)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(Constants.APP_ICON)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), Constants.APP_ICON))
                .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)// 屏幕可见性，锁屏时，显示icon和标题，内容隐藏
                .setNumber(999)// 自定义桌面通知数量
                .setAutoCancel(true)// 是否自动消失（点击）or mManager.cancel(mNormalNotificationId)、cancelAll、setTimeoutAfter()

                ;

        //通过 builder.build() 拿到 notification
        mNotificationManager.notify(SharedPreferenceUtils.getNextNoticeId(this), mBuilder.build());
    }


}